<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>拖动div</title>

    <style>
        body{
            height: 500px;
            width: 500px;
            border: 1px solid black;
            position: relative;
        }

        #divPhoto {
            height: 50px;
            width: 50px;
            position: absolute;
            background-color: red;
        }
    </style>
</head>
<body>
<div id="divPhoto" onmousedown="drag(event,this)"></div>


<script>
    //定义鼠标拖动对象
    drag = function (a, o) {
        var d = document;
        if (!a) a = window.event;

        //元素相对位置
        if (!a.pageX) a.pageX = a.clientX;
        if (!a.pageY) a.pageY = a.clientY;
        var x = a.pageX, y = a.pageY;


        //处理一个 mousedown 事件过程中调用这个方法来把全部的鼠标事件重新定向到这个元素，直到鼠标按钮被释放或者 document.releaseCapture() 被调用。
        if (o.setCapture) {
            o.setCapture();
        }
        else if (window.captureEvents) {
            window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
        }


        var backData = {x: o.style.top, y: o.style.left};
        d.onmousemove = function (a) {
            if (!a) a = window.event;
            if (!a.pageX) a.pageX = a.clientX;
            if (!a.pageY) a.pageY = a.clientY;
            var tx = a.pageX - x + parseInt(o.style.left || o.offsetLeft || 0), ty = a.pageY - y + parseInt(o.style.top || o.offsetTop || 0);

            if (!document.body.pageWidth) document.body.pageWidth = document.body.clientWidth;
            if (!document.body.pageHeight) document.body.pageHeight = document.body.clientHeight;


            //超出边界，以边界为终点
            if(tx > document.body.pageWidth){
                o.style.left = document.body.pageWidth - o.clientWidth + "px";
            }else{
                o.style.left = tx + "px";
            }
            if(ty > document.body.pageHeight){
                o.style.top = document.body.pageHeight - o.clientHeight + "px";
            }else{
                o.style.top = ty + "px";
            }
            x = a.pageX;
            y = a.pageY;
        };
        d.onmouseup = function (a) {
            if (!a) a = window.event;
            if (o.releaseCapture)
                o.releaseCapture();
            else if (window.captureEvents)
                window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);

            d.onmousemove = null;
            d.onmouseup = null;
            if (!a.pageX) a.pageX = a.clientX;
            if (!a.pageY) a.pageY = a.clientY;
            if (!document.body.pageWidth) document.body.pageWidth = document.body.clientWidth;
            if (!document.body.pageHeight) document.body.pageHeight = document.body.clientHeight;

            //满足条件，恢复初始位置
            if (a.pageX < 1 || a.pageY < 1 || a.pageX > document.body.pageWidth || a.pageY > document.body.pageHeight) {
                o.style.left = backData.y;
                o.style.top = backData.x;
            }
        };
    }
</script>
</body>
</html>